import { createRouter, createWebHistory } from "vue-router";
import { routes } from "./routes";
import ACCESS_ENUM from "@/access/accessEnum";
import { useStore } from "vuex";

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {     // 在跳转路由之前判断
  const store = useStore();
  // 仅管理员可见
  store.dispatch("user/initializeUser", {});
  if (to.meta?.access === ACCESS_ENUM.ADMIN) {
    if (store.state.user.user?.permission !== "1") {
      next("/login");
      return;
    }
  } else if (to.meta?.access !== ACCESS_ENUM.SIGNING || !to.meta) {   // 如果不是登入页面并且还没有登入
    if (store.state.user.user?.status !== "Login") {
      next("/login");
      return;
    }
  } else if (to.meta?.access === ACCESS_ENUM.SIGNING && store.state.user.user?.status === "Login") {
    next("/");
    return;
  }
  next();
});

export default router;
